package com.basic.library.view

import android.annotation.SuppressLint
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.Observer
import com.jeremyliao.liveeventbus.LiveEventBus

/**
 * @author yj
 * @description
 */
@SuppressLint("StaticFieldLeak")
object ClockTickUtil {
    var context: Context? = null
    const val Tick = "TimeTick"

    private val broadcast = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            if (intent.action == Intent.ACTION_TIME_TICK) {
                LiveEventBus.get(Tick).post(null)
            }
        }
    }

    fun observe(owner: LifecycleOwner, observer: Observer<Any>) {
        LiveEventBus.get(Tick, Any::class.java).observe(owner, observer)
        LiveEventBus.get(Tick).postDelay(null, 50)
    }

    fun registerReceiver(context: Context) {
        ClockTickUtil.context = context
        val filter = IntentFilter()
        filter.addAction(Intent.ACTION_TIME_TICK)
        context.registerReceiver(broadcast, filter)
    }

    fun unregisterReceiver() {
        context?.unregisterReceiver(broadcast)
    }
}